package com.syp.test.clustercacheflush.scheduled.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.syp.test.clustercacheflush.domain.TaskEntity;
import com.syp.test.clustercacheflush.handler.TaskProcessHandler;
import com.syp.test.clustercacheflush.scheduled.GeneralCronScheduled;
import com.syp.test.clustercacheflush.service.TaskService;
import com.syp.test.clustercacheflush.service.TaskType;
import com.syp.test.clustercacheflush.util.Constants;
import com.syp.test.clustercacheflush.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 处理任务Scheduled,该Scheduled一直处于运行状态
 * 
 * @author syp
 * @update 2016年7月14日 下午10:16:45
 */
@Component
@Slf4j
public class TaskProcessScheduled implements GeneralCronScheduled {

	@Resource(name = "taskProcessExecutor")
	private ThreadPoolTaskExecutor taskProcessExecutor;
	@Autowired
	private TaskService taskService;

	@Scheduled(cron = Constants.CRON_EVERY_2_SECONDS)
	@Override
	public void dispatch() {
		List<TaskEntity> processList = this.taskService.getWaitToProcessTask();
		if (processList != null && !processList.isEmpty()) {
			processList.forEach(task -> {
				boolean success = this.taskService.lock(task);
				if (success) {
					this.taskProcessExecutor.execute(() -> {
						boolean done = false;
						try {
							log.debug("执行任务内容:{}", JSON.toJSONString(task));
							TaskType taskType = TaskType.get(task.getTaskType());
							TaskProcessHandler processor = SpringContextUtil.getBean(taskType.getExecutor());
							done = processor.process(task);
							if(done){
								this.taskService.finish(task);
							}
						} catch (Exception e) {
							log.error("执行任务异常:{}", e);
						}
					});
				}
			});
		}
	}
}
